package com.cloud.cloudshop.exception;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.cloud.common.utils.R;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 54485
 */
@RestControllerAdvice
public class GlobalExceptionHandler {


    @ExceptionHandler(value = Exception.class)
    public R globalErrorHandler(Exception ex) {
        if(ex instanceof UserException){
            return R.error(((UserException) ex).getCode(),ex.getMessage());
        }else {
            ex.printStackTrace();
            return R.error(ex.getMessage());
        }
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R MethodArgumentNotValidExceptionHandler(Exception ex) {
        Map<String,String> errorMesssage = new HashMap<>();
        BindingResult bindingResult = ((MethodArgumentNotValidException) ex).getBindingResult();
        if(bindingResult!=null&& CollectionUtils.isNotEmpty(bindingResult.getFieldErrors())){
            for (FieldError fieldError : bindingResult.getFieldErrors()) {
                errorMesssage.put(fieldError.getField(),fieldError.getDefaultMessage());
            }
        }
        return R.error(400,"数据校验未通过").put("data",errorMesssage);
    }




}
